package com.scorpio.security.interceptor;

import com.scorpio.agentuser.domain.AgentUserEntity;
import com.scorpio.agentuser.service.AgentUserService;
import com.scorpio.common.constant.Constants;
import com.scorpio.common.constant.AppHttpStatus;
import com.scorpio.common.exception.CustomException;
import com.scorpio.security.user.LoginUser;
import com.scorpio.security.annotation.PersonalLogin;
import com.scorpio.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人用户登录拦截器
 */
@Component
public class PersonalAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AgentUserService personalService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PersonalLogin annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PersonalLogin.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }

        String token = tokenService.getToken(request);
        LoginUser loginUser = tokenService.getLoginUser(token);
        if (loginUser == null) {
            if (StringUtils.isEmpty(token)) {
                throw new CustomException("请登录后操作", AppHttpStatus.UNAUTHORIZED);
            } else {
                throw new CustomException("登录信息异常", AppHttpStatus.FORBIDDEN);
            }
        } else if ("1".equals(loginUser.getIsStrongBack())) {
            tokenService.removeToken(loginUser);
            throw new CustomException("已在其他设备登录", AppHttpStatus.FORBIDDEN);
        }
        tokenService.verifyToken(loginUser);

        AgentUserEntity entity = personalService.selectById(Long.valueOf(loginUser.getUniqueId()));
        if (entity == null) {
            throw new CustomException("登录信息异常", AppHttpStatus.FORBIDDEN);
        }
        request.setAttribute(Constants.LOGIN_USER_KEY, entity);
        return super.preHandle(request, response, handler);
    }
}
